using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MinoChat.Data.Entities;
using MinoChat.Data.Services.Interfaces;
using MinoChat.Services.Interfaces;
using System.Collections.ObjectModel;

namespace MinoChat.ViewModels.Pages;

public partial class SearchPageViewModel : ObservableObject
{
    private readonly IChatSearchService _searchService;
    private readonly INavigationService _navigationService;

    [ObservableProperty]
    private string _searchKeyword = string.Empty;

    [ObservableProperty]
    private ObservableCollection<ChatMessage> _searchResults = new();

    [ObservableProperty]
    private bool _isSearching = false;

    [ObservableProperty]
    private bool _hasSearched = false;

    [ObservableProperty]
    private string _searchPlaceholder = "搜索聊天历史记录...";

    public SearchPageViewModel(IChatSearchService searchService, INavigationService navigationService)
    {
        _searchService = searchService;
        _navigationService = navigationService;
    }

    [RelayCommand]
    private async Task SearchAsync()
    {
        if (string.IsNullOrWhiteSpace(SearchKeyword))
        {
            return;
        }

        IsSearching = true;
        HasSearched = true;
        SearchResults.Clear();

        try
        {
            var results = await _searchService.SearchMessagesAsync(SearchKeyword.Trim());

            foreach (var message in results)
            {
                SearchResults.Add(message);
            }
        }
        catch (Exception ex)
        {
            // TODO: 显示错误消息
            System.Diagnostics.Debug.WriteLine($"搜索出错: {ex.Message}");
        }
        finally
        {
            IsSearching = false;
        }
    }

    [RelayCommand]
    private void ClearSearch()
    {
        SearchKeyword = string.Empty;
        SearchResults.Clear();
        HasSearched = false;
    }

    [RelayCommand]
    private void ClosePage()
    {
        _navigationService.GoBack();
    }
}
